<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-7-20
 * Time: 上午8:45
 */

namespace api\modules\chedai\controllers;


use Cloudauth\Request\V20171117\CompareFacesRequest;
use Cloudauth\Request\V20171117\GetMaterialsRequest;
use Cloudauth\Request\V20171117\GetStatusRequest;
use Cloudauth\Request\V20171117\GetVerifyTokenRequest;
use common\components\ali\AppStore;
use common\components\ali\Config;
use common\components\tools\FileHelper;
use common\components\tools\Model;
use common\components\tools\Tools;
use common\models\AliCarinfoGetLog;
use common\models\AliFaceValidate;
use common\models\credit_app\Order;
use common\models\credit_app\OrderCar;
use wodrow\yii\rest\Controller;
use wodrow\yii\rest\ApiException;
use yii\base\ErrorException;
use yii\base\Exception;

class AliController extends Controller
{
    /**
     * 发起认证请求 [暂时只给token值]
     * @desc 描述 接口名称： GetVerifyToken 功能描述： 每次开始认证前通过GetVerifyToken接口获取认证 Token，VerifyToken参数用来串联认证请求中的各个接口。名词解释 业务场景 Biz： 表示使用实人认证服务的业务场景，请先参考 业务设置 在控制台上完成创建。认证 ID TicketId： 标识一次认证任务的唯一 ID，通常由业务使用方指定，方便关联业务场景的其他内容。一次认证任务，系统支持无限次发起提交，直到最终认证通过该任务完结。注意：发起不同的认证任务时需要更换不同的认证 ID。图片地址格式： 用来告诉实人认证服务如何获取到图片，图片地址描述有以下几种模式： http： 一个可访问的公网 HTTP 地址，例如 http://image-demo.img-cn-hangzhou.aliyuncs.com/example.jpg。 oss： 一个可公开访问的 OSS 文件地址，格式为 oss://<bucket>:<path_to_file>。 base64: 一个 base64 编码的图片，格式为 base64://<图片 base64 字符串>。 注意：不支持本地图片的相对路径或绝对路径。单张图片大小请控制在 2M 内，避免算法拉取超时。单个请求的 Body 有 8M 的大小限制，请计算好请求中所有图片和其他信息的大小，不要超限。使用 base64 传递图片的时候，SubmitMaterials的请求方法需要改成 POST；图片 base64 字符串需要去掉头部描述，如data:image/png;base64,。
     * @param string $name 姓名
     * @param string $idcard 身份证号
     */
    public function actionAuth($name, $idcard, $idcard_f = null, $idcard_b = null)
    {
        $iClientProfile = \DefaultProfile::getProfile(
            "cn-hangzhou",            //默认
            Config::KEY_ID,        //您的Access Key ID
            Config::KEY_SECRET);    //您的Access Key Secret
        $iClientProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", "Cloudauth", "cloudauth.aliyuncs.com");
        $client = new \DefaultAcsClient($iClientProfile);
        $biz = "UserRegister"; //您在控制台上创建的、采用RPBasic认证方案的认证场景标识, 创建方法：https://help.aliyun.com/document_detail/59975.html
        $ticketId = date("YmdHis_").\Yii::$app->security->generateRandomString(5); //认证ID, 由使用方指定, 发起不同的认证任务需要更换不同的认证ID
        $token = null; //认证token, 表达一次认证会话
        $statusCode = -1; //-1 未认证, 0 认证中, 1 认证通过, 2 认证不通过
        $getVerifyTokenRequest = new GetVerifyTokenRequest();
        $getVerifyTokenRequest->setBiz($biz);
        $getVerifyTokenRequest->setTicketId($ticketId);
        $json = <<<JSON
{
    "Name": "{$name}",
    "IdentificationNumber": "{$idcard}"
}
JSON;
        $getVerifyTokenRequest->setBinding($json);
        try {
            $response = $client->getAcsResponse($getVerifyTokenRequest);
            $token = $response->Data->VerifyToken->Token; //token默认30分钟时效，每次发起认证时都必须实时获取
        } catch (Exception $e) {
//            print $e->getTrace();
            throw $e;
        }
        return $token;
    }

    /**
     * 发起认证请求 [暂时只给token值]
     * @desc 描述 接口名称： GetVerifyToken 功能描述： 每次开始认证前通过GetVerifyToken接口获取认证 Token，VerifyToken参数用来串联认证请求中的各个接口。名词解释 业务场景 Biz： 表示使用实人认证服务的业务场景，请先参考 业务设置 在控制台上完成创建。认证 ID TicketId： 标识一次认证任务的唯一 ID，通常由业务使用方指定，方便关联业务场景的其他内容。一次认证任务，系统支持无限次发起提交，直到最终认证通过该任务完结。注意：发起不同的认证任务时需要更换不同的认证 ID。图片地址格式： 用来告诉实人认证服务如何获取到图片，图片地址描述有以下几种模式： http： 一个可访问的公网 HTTP 地址，例如 http://image-demo.img-cn-hangzhou.aliyuncs.com/example.jpg。 oss： 一个可公开访问的 OSS 文件地址，格式为 oss://<bucket>:<path_to_file>。 base64: 一个 base64 编码的图片，格式为 base64://<图片 base64 字符串>。 注意：不支持本地图片的相对路径或绝对路径。单张图片大小请控制在 2M 内，避免算法拉取超时。单个请求的 Body 有 8M 的大小限制，请计算好请求中所有图片和其他信息的大小，不要超限。使用 base64 传递图片的时候，SubmitMaterials的请求方法需要改成 POST；图片 base64 字符串需要去掉头部描述，如data:image/png;base64,。
     * @param string $name 姓名
     * @param string $idcard 身份证号
     */
    public function actionAuth1($name, $idcard, $idcard_f = null, $idcard_b = null)
    {
        $iClientProfile = \DefaultProfile::getProfile(
            "cn-hangzhou",            //默认
            Config::KEY_ID,        //您的Access Key ID
            Config::KEY_SECRET);    //您的Access Key Secret
        $iClientProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", "Cloudauth", "cloudauth.aliyuncs.com");
        $client = new \DefaultAcsClient($iClientProfile);
        $biz = "UserRegister"; //您在控制台上创建的、采用RPBasic认证方案的认证场景标识, 创建方法：https://help.aliyun.com/document_detail/59975.html
        $ticketId = date("YmdHis_").\Yii::$app->security->generateRandomString(5); //认证ID, 由使用方指定, 发起不同的认证任务需要更换不同的认证ID
        $token = null; //认证token, 表达一次认证会话
        $statusCode = -1; //-1 未认证, 0 认证中, 1 认证通过, 2 认证不通过
        $getVerifyTokenRequest = new GetVerifyTokenRequest();
        $getVerifyTokenRequest->setBiz($biz);
        $getVerifyTokenRequest->setTicketId($ticketId);
        $json = <<<json
{
    "Name": "{$name}",
    "IdentificationNumber": "{$idcard}"
}
json;
        $getVerifyTokenRequest->setBinding($json);
        try {
            $response = $client->getAcsResponse($getVerifyTokenRequest);
            $ali_fv = new AliFaceValidate();
            $ali_fv->idcard = $idcard;
            $ali_fv->name = $name;
            $ali_fv->created_at = time();
            $ali_fv->uid = \Yii::$app->chedai_user->id;
            $ali_fv->ticket_id = $ticketId;
            if (!$ali_fv->save()){
                throw new ErrorException("阿里人脸认证保存失败".var_export($ali_fv->errors, true));
            }
            $token = $response->Data->VerifyToken->Token; //token默认30分钟时效，每次发起认证时都必须实时获取
        } catch (Exception $e) {
            print $e->getTrace();
            throw $e;
        }
        return [
            'token' => $token,
            'ticketId' => $ticketId,
        ];
    }

    /**
     * 保存人脸识别结果
     * @desc get/post
     * @param string $audit
     * @param string $idcard
     * @param string $name
     * @param string $client_type
     * @return array
     * @throws ErrorException
     */
    public function actionSaveAliFaceValidateResult($audit, $idcard, $name, $client_type)
    {
        $r = [];
        $ali_fv = new AliFaceValidate();
        $ali_fv->audit = $audit;
        $ali_fv->idcard = $idcard;
        $ali_fv->name = $name;
        $ali_fv->client_type = $client_type;
        $ali_fv->created_at = time();
        $ali_fv->uid = \Yii::$app->chedai_user->id;
        if (!$ali_fv->save()){
            throw new ErrorException("阿里人脸认证保存失败".var_export($ali_fv->errors, true));
        }
        $r['ali_fv'] = $ali_fv->toArray();
        return $r;
    }

    /**
     * 保存人脸识别结果
     * @desc get/post
     * @param string $audit
     * @param string $idcard
     * @param string $name
     * @param string $client_type
     * @return array
     * @throws ErrorException
     * @throws ApiException
     */
    public function actionSaveAliFaceValidateResult1($ticket_id, $audit, $client_type)
    {
        $r = [];
        $ali_fv = AliFaceValidate::findOne(['ticket_id' => $ticket_id]);
        if (!$ali_fv){
            throw new ApiException(201810161026, "数据库没有找到人脸识别数据");
        }
        $ali_fv->audit = $audit;
        $ali_fv->client_type = $client_type;
        if (!$ali_fv->save()){
            throw new ErrorException("阿里人脸认证保存失败".var_export($ali_fv->errors, true));
        }
        $r['ali_fv'] = $ali_fv->toArray();
        return $r;
    }

    /**
     * 根据身份证获取阿里人脸识别的信息
     * @desc get/post
     * @param $idcard
     * @return array
     */
    public function actionGetAliFaceValidateByIdcard($idcard)
    {
        $r = [];
        $ali_fv = AliFaceValidate::findOne(['idcard' => $idcard, 'audit' => AliFaceValidate::AUDIT_PASS]);
        if (!$ali_fv){
            $ali_fv = AliFaceValidate::findOne(['idcard' => $idcard, 'audit' => AliFaceValidate::AUDIT_FAIL]);
            if (!$ali_fv){
                $ali_fv = AliFaceValidate::findOne(['idcard' => $idcard, 'audit' => AliFaceValidate::AUDIT_EXCEPTION]);
                if (!$ali_fv){
                    $ali_fv = AliFaceValidate::findOne(['idcard' => $idcard, 'audit' => AliFaceValidate::AUDIT_NOT]);
                    if (!$ali_fv){
                        $ali_fv = new AliFaceValidate();
                        $ali_fv->audit = AliFaceValidate::AUDIT_NOT;
                    }
                }
            }
        }
        /*if (!$ali_fv){
            $ali_fv = AliFaceValidate::find()->where(['idcard' => $idcard,])->orderBy(['created_at' => SORT_DESC])->one();
            if (!$ali_fv){
                $ali_fv = new AliFaceValidate();
                $ali_fv->audit = AliFaceValidate::AUDIT_NOT;
            }
        }*/
        $r['ali_fv'] = $ali_fv->toArray();
        return $r;
    }

    /**
     * 获取认证资料
     * @desc
    接口名称： GetMaterials

    功能描述： 用户在云服务提交认证后，业务系统通过GetMaterials接口获取用户上传的资料（人脸图、证件图）及算法识别的资料（OCR 的地址等）。

    名词解释
    业务场景 Biz： 表示使用实人认证服务的业务场景，请先参考 业务设置 在控制台上完成创建。
    认证 ID TicketId： 标识一次认证任务的唯一 ID，通常由业务使用方指定，方便关联业务场景的其他内容。
     * @param string $ticket_id 标识一次认证任务的唯一 ID，通常由业务使用方指定，方便关联业务场景的其他内容。
     * @throws
     */
    public function actionGetMaterials($ticket_id)
    {
        $ali_fv = AliFaceValidate::findOne(['ticket_id' => $ticket_id]);
        if (!$ali_fv){
            throw new ApiException(201810161100, "数据库没有找到人脸识别数据");
        }
        $statusCode = $ali_fv->audit;
        $iClientProfile = \DefaultProfile::getProfile(
            "cn-hangzhou",         // 默认
            Config::KEY_ID,        // 您的Access Key ID
            Config::KEY_SECRET);    // 您的Access Key Secret
        $iClientProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", "Cloudauth", "cloudauth.aliyuncs.com");
        $client = new \DefaultAcsClient($iClientProfile);
        $biz = "UserRegister"; // 您在控制台上创建的、采用RPBasic认证方案的认证场景标识,
        // 7. 服务端获取认证资料 //GetMaterials接口文档：https://help.aliyun.com/document_detail/57641.html
        $getMaterialsRequest = new GetMaterialsRequest();
        $getMaterialsRequest->setBiz($biz);
        $getMaterialsRequest->setTicketId($ticket_id);
        if (1 == $statusCode or 2 == $statusCode) {
            try {
                $response = $client->getAcsResponse($getMaterialsRequest);
                $resp_data = $response->Data;
                $rd = Tools::objectToArray($resp_data);
                return [
                    '_resp_data' => $resp_data,
                    'rd' => $rd,
                ];
            } catch (\ServerException $e) {
                print $e->getMessage();
            } catch (\ClientException $e) {
                print $e->getMessage();
            }
        }else{
            throw new ApiException(201810161103, "认证通过or认证不通过");
        }
    }

    /**
     * 人脸比对验证
     * @desc get/post
     * @param string $ticket_id 标识一次认证任务的唯一 ID，通常由业务使用方指定，方便关联业务场景的其他内容。
     * @throws
     */
    public function actionFaceComparison($ticket_id)
    {
        $ali_fv = AliFaceValidate::findOne(['ticket_id' => $ticket_id]);
        if (!$ali_fv){
            throw new ApiException(201810161100, "数据库没有找到人脸识别数据");
        }
        $r = $this->actionGetMaterials($ticket_id);
        //创建DefaultAcsClient实例并初始化
        $iClientProfile = \DefaultProfile::getProfile(
            "cn-hangzhou",            //默认
            Config::KEY_ID,        //您的Access Key ID
            Config::KEY_SECRET);    //您的Access Key Secret
        $iClientProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", "Cloudauth", "cloudauth.aliyuncs.com");
        $client = new \DefaultAcsClient($iClientProfile);
        //创建API请求并设置参数
        //CompareFaces接口文档：https://help.aliyun.com/document_detail/59317.html
        $request = new CompareFacesRequest();
        //若使用base64上传图片, 需要设置请求方法为POST
        $request->setMethod("POST");
        //传入图片资料，请控制单张图片大小在 2M 内，避免拉取超时
        $request->setSourceImageType("IDPic");
        $request->setSourceImageValue($r['rd']['IdCardFrontPic']);
        $request->setTargetImageType("FacePic");
        $request->setTargetImageValue($r['rd']['FacePic']);
        try {
            $response = $client->getAcsResponse($request);
            $resp_data = $response->Data;
            $rd = Tools::objectToArray($resp_data);
            $rd['ConfidenceThresholds'] = json_decode($rd['ConfidenceThresholds'], true);
            return [
                '_resp_data' => $resp_data,
                'rd' => $rd,
            ];
        } catch (\ServerException $e) {
            print $e->getMessage();
        } catch (\ClientException $e) {
            print $e->getMessage();
        } //常见问题：https://help.aliyun.com/document_detail/57640.html
    }

    /**
     * 发票核验接口并返回发票信息（发票） 扫_描二维码 乐税发票真伪查验接口
     * @desc get/post https://market.aliyun.com/products/56928005/cmapi026291.html
     * @param string $scanStr 二维码字符串
     * @param string $o_id 订单号
     * @throws
     */
    public function actionScanQrCodeInvoiceAuthenticityInspectionInterface($scanStr = null, $o_id)
    {
        $log = new AliCarinfoGetLog();
        $log->o_id = $o_id;
        $log->uid = \Yii::$app->chedai_user->identity->u_id;
        $log->type = AliCarinfoGetLog::TYPE_FPZW;
        $log->created_at = time();
        $log->request_fpzw_str = $scanStr;
        if ($scanStr){
            $body = AppStore::scanQrCodeInvoiceAuthenticityInspectionInterface($scanStr);
            $arr = json_decode($body, true);
            $log->url = 'https://ls365vat.market.alicloudapi.com';
            $log->RtnCode = $arr['RtnCode'];
            $log->resultCode = $arr['resultCode'];
            $log->invoicefalseCode = isset($arr['invoicefalseCode'])?$arr['invoicefalseCode']:null;
            $log->resultMsg = $arr['resultMsg'];
            $log->invoiceName = $arr['invoiceName'];
            $log->invoiceResult = json_encode($arr['invoiceResult']);
            $log->isFree = isset($arr['isFree'])?$arr['isFree']:null;
            $log->invoiceDataCode = $log->fpdm = isset($arr['invoiceResult']['invoiceDataCode'])?$arr['invoiceResult']['invoiceDataCode']:null;
            $log->invoiceNumber = $log->fphm = isset($arr['invoiceResult']['invoiceNumber'])?$arr['invoiceResult']['invoiceNumber']:null;
            $log->billingTime = $log->kprq = isset($arr['invoiceResult']['billingTime'])?$arr['invoiceResult']['billingTime']:null;
            $log->checkCode = isset($arr['invoiceResult']['checkCode'])?$arr['invoiceResult']['checkCode']:null;
            $log->vehicle_type = $log->car_type = isset($arr['invoiceResult']['vehicleType'])?$arr['invoiceResult']['vehicleType']:null; // 车辆类型
            $log->engine_num = $log->engine_number = isset($arr['invoiceResult']['engineNumber'])?$arr['invoiceResult']['engineNumber']:null; // 发动机号码
            $log->plate_num = isset($arr['invoiceResult']['plateNo'])?$arr['invoiceResult']['plateNo']:null; // 老的车牌号
            $log->invoice_created_date = $log->kprq = $log->billingTime; // 发票开票日期
            $log->invoice_number = $log->fphm = isset($arr['invoiceResult']['invoiceNumber'])?$arr['invoiceResult']['invoiceNumber']:null; // 发票号码
        }else{
            $body = '';
        }
        $log->resp_body = $body;
        if (!$log->save()){
            throw new ApiException(201811141356, Model::getModelError($log));
        }
//        \Yii::$app->trigger(\Yii::$app::EVENT_AFTER_ACTION);
        echo $body;exit;
    }

    /**
     * VIN识别接口（提车影像）
     * @desc get/post https://market.aliyun.com/products/57124001/cmapi023049.html?spm=5176.2020520132.101.10.29cc72185cOeU1#sku=yuncode1704900000
     * @param string $file_url 文件获取url
     * @param string $o_id 订单号
     * @throws
     */
    public function actionPrintedWordRecognitionVehicleIdentification($file_url = null, $o_id)
    {
        $log = new AliCarinfoGetLog();
        $log->o_id = $o_id;
        $log->uid = \Yii::$app->chedai_user->identity->u_id;
        $log->type = AliCarinfoGetLog::TYPE_VIN;
        $log->created_at = time();
        $log->request_file_url = $file_url;
        if ($file_url){
            $file_path = FileHelper::downloadTmpFileFromUrl($file_url);
            $body = AppStore::printedWordRecognitionVehicleIdentification($file_path);
            $arr = json_decode($body, true);
            $log->url = 'https://vin.market.alicloudapi.com/api/predict/ocr_vin';
            $log->vin = $arr['vin'];
            $log->request_id = $arr['request_id'];
            $log->success = $arr['success']?1:0;
        }else{
            $body = '';
        }
        $log->resp_body = $body;
        if (!$log->save()){
            throw new ApiException(201811141355, Model::getModelError($log));
        }
//        \Yii::$app->trigger(\Yii::$app::EVENT_AFTER_ACTION);
        echo $body;exit;
    }

    /**
     * 合格证二维码密文解码接口（合格证） 《机动车合格证》二维码解码
     * @desc get/post https://www.apishop.net/#/api/detail/?productID=216
     * @param string $encText 《机动车合格证》二维码未解码之前的密文，类似：ZCCCHGZ_V3.1 20091013#1280|C206A……
     * @param string $o_id 订单号
     * @throws
     */
    public function actionQrCodeTextDecoding($encText = null, $o_id)
    {
        $log = new AliCarinfoGetLog();
        $log->o_id = $o_id;
        $log->uid = \Yii::$app->chedai_user->identity->u_id;
        $log->type = AliCarinfoGetLog::TYPE_HGZ;
        $log->created_at = time();
        $log->request_hgz_text = $encText;
        if ($encText&&substr($encText, 0, 7) == 'ZCCCHGZ'){
            $body = AppStore::qrCodeTextDecoding($encText);
            $arr = json_decode($body, true);
            $log->url = 'https://api.apishop.net/ccdfeege/vin123';
            $log->success = $arr['success']?1:0;
            $log->result = $arr['result'];
            $log->ret_code = $arr['ret_code'];
            $log->comment = $arr['comment'];
            if (isset($arr['data'])){
                $log->data = json_encode($arr['data']);
                $log->vehicle_type = $log->car_type = $arr['data']['车辆类型']; // 车辆类型
                $x = Tools::str2arr($arr['data']['车辆品牌'], "/");
                $log->car_model = $log->model = $x[0].$arr['data']['车辆型号']; // 车辆型号
                $log->vin = $arr['data']['车架号'];  // 车架号
                $log->car_color = $arr['data']['车身颜色'];  // 车身颜色
                $log->engine_number = $log->engine_num = $arr['data']['发动机号'];
            }
        }else{
            $body = '';
        }
        $log->resp_body = $body;
        if (!$log->save()){
            throw new ApiException(201811141354, Model::getModelError($log));
        }
//        \Yii::$app->trigger(\Yii::$app::EVENT_AFTER_ACTION);
        echo $body;exit;
    }

    /**
     * 行驶证OCR识别接口（行驶证） 印刷文字识别_行驶证识别
     * @desc get/post https://market.aliyun.com/products/57002003/cmapi011791.html
     * @param string $file_url 文件获取url
     * @param string $side 正反面face/back
     * @param string $o_id 订单号
     * @throws
     */
    public function actionPrintedCharacterRecognitionLicenseRecognition($file_url = null, $side = 'face', $o_id)
    {
        $log = new AliCarinfoGetLog();
        $log->o_id = $o_id;
        $log->uid = \Yii::$app->chedai_user->identity->u_id;
        $log->created_at = time();
        $log->request_file_url = $file_url;
        switch ($side){
            case 'face':
                $log->type = AliCarinfoGetLog::TYPE_XSZZ;
                break;
            case 'back':
                $log->type = AliCarinfoGetLog::TYPE_XSZY;
                break;
            default:
                throw new ApiException(201811141405, 'must face/back');
                break;
        }
        if ($file_url){
            $file_path = FileHelper::downloadTmpFileFromUrl($file_url);
            $body = AppStore::printedCharacterRecognitionLicenseRecognition($file_path, $side);
            $arr = json_decode($body, true);
            $log->url = 'https://dm-53.data.aliyun.com/rest/160601/ocr/ocr_vehicle.json';
            $log->success = $arr['success']?1:0;
            $log->request_id = $arr['request_id'];
            switch ($side){
                case 'face':
                    $log->type = AliCarinfoGetLog::TYPE_XSZZ;
                    $log->plate_num = $arr['plate_num'];       #车牌号码
                    $log->vehicle_type = $log->car_type = $arr['vehicle_type'];      #车辆类型
                    $log->owner = $log->license_driver = $arr['owner'];               #所有人名称
                    $log->use_character = $arr['use_character'];     #使用性质
                    $log->addr = $arr['addr'];#地址
                    $log->model =$arr['model'];   #品牌型号
                    $log->vin  = $arr['vin'];    #车辆识别代号
                    $log->engine_num = $log->engine_number = $arr['engine_num'];       #发动机号码
                    $log->register_date = $arr['register_date'];      #注册日期
                    $log->issue_date = $arr['issue_date'];       #发证日期
                    break;
                case 'back':
                    $log->type = AliCarinfoGetLog::TYPE_XSZY;
                    $log->config_str = $arr['config_str'];;  #配置字符串信息
                    $log->appproved_passenger_capacity = $arr['appproved_passenger_capacity'];;    #核定载人数
                    $log->approved_load = $arr['approved_load'];;                      #核定载质量
                    $log->file_no = $arr['file_no'];;                #档案编号
                    $log->gross_mass = $arr['gross_mass'];;                   #总质量
                    $log->inspection_record = $arr['inspection_record'];;  #检验记录
                    $log->overall_dimension = $arr['overall_dimension'];;   #外廓尺寸
                    $log->traction_mass = $arr['traction_mass'];;                       #准牵引总质量
                    $log->unladen_mass = $arr['unladen_mass']; ;                  #整备质量
                    $log->plate_num = $arr['plate_num'];;                   #号牌号码
                    break;
                default:
                    throw new ApiException(201811141405, 'must face/back');
                    break;
            }
        }else{
            $body = '';
        }
        $log->resp_body = $body;
        if (!$log->save()){
            throw new ApiException(201811141353, Model::getModelError($log));
        }else{
            $app_car = OrderCar::findOne(['ot_oid' => $o_id]);
            if (!$app_car->ot_cartp)$app_car->ot_cartp = $log->vehicle_type;
            if (!$app_car->ot_carmodels)$app_car->ot_carmodels = $log->model;
            if (!$app_car->ot_carno){
                if (strlen($log->vin) == 17){
                    $app_car->ot_carno = $log->vin;
                    $app_car->ot_chassisno = substr($log->vin, -6);
                }
            }
            if (!$app_car->ot_engineno)$app_car->ot_engineno = $log->engine_num;
            if (strlen($log->register_date) == 8){
                $app_car->ot_initialrg_time = date("Y-m-d", strtotime($log->register_date));
            }
            if (!$app_car->ot_car_platenum)$app_car->ot_car_platenum = $log->plate_num;
            if (!$app_car->save(false)){
                throw new ApiException(201812061451, Model::getModelError($app_car));
            }
        }
        return [
            'plat_resp' => $body,
            'other_data' => json_decode($body, true),
        ];
    }

    /**
     * 发票OCR识别接口（发票） OCR识别
     * @desc get/post 【购车发票识别、机动车发票识别、发票查验、发票验真】 https://market.aliyun.com/products/57124001/cmapi030552.html
     * @param string $file_url 文件获取url
     * @param string $o_id 订单号
     * @param string $new_or_used 新车/二手车 newcar/usedcar
     * @throws
     */
    public function actionOcrDistinguishing($file_url = null, $o_id, $new_or_used)
    {
        $log = new AliCarinfoGetLog();
        $log->o_id = $o_id;
        $log->uid = \Yii::$app->chedai_user->identity->u_id;
        $log->type = AliCarinfoGetLog::TYPE_FPOCRZW;
        $log->created_at = time();
        $log->request_file_url = $file_url;
        $log->request_new_or_used = $new_or_used;
        if ($file_url){
            $file_path = FileHelper::downloadTmpFileFromUrl($file_url);
            $body = AppStore::ocrDistinguishing($file_path, $new_or_used);
            $arr = json_decode($body, true);
            $log->url = 'http://gcfp.market.alicloudapi.com';
            $log->Code = (string)$arr['Code'];
            $log->Message = $arr['Message'];
            $log->RequsetId = $log->request_id = isset($arr['RequestId'])?$arr['RequestId']:null;
            if (isset($arr['data'])){
                $log->data = json_encode($arr['Data']);
                $log->fpdm = $log->invoiceDataCode = $arr['Data']['fpdm'];
                $log->fphm = $log->invoice_number = $arr['Data']['fphm'];
                $log->kprq = $log->invoice_created_date = $log->billingTime = $arr['Data']['kprq'];
                $log->num = $arr['Data']['num'];
                $log->vin = $arr['Data']['cjh'];
            }
        }else{
            $body = '';
        }
        $log->resp_body = $body;
        if (!$log->save()){
            throw new ApiException(201811141352, Model::getModelError($log));
        }
//        \Yii::$app->trigger(\Yii::$app::EVENT_AFTER_ACTION);
        echo $body;exit;
    }

    /**
     * 登记证书第一页
     * @desc get/post
     * @param string $str 条形码字符串
     * @param string $o_id 订单号
     * @throws
     */
    public function actionDjzsFirstPage($str = null, $o_id)
    {
        $log = new AliCarinfoGetLog();
        $log->o_id = $o_id;
        $log->uid = \Yii::$app->chedai_user->identity->u_id;
        $log->type = AliCarinfoGetLog::TYPE_DJZS;
        $log->created_at = time();
        $log->resp_body = '';
        $log->url = null;
        $log->request_djzs_str = $str;
        if ($str){
            $log->success = 1;
        }else{
            $log->success = 0;
        }
        if (!$log->save()){
            throw new ApiException(201811141351, Model::getModelError($log));
        }
    }

    /**
     * 印刷文字识别-机动车发票识别
     * @desc get/post 印刷文字识别-机动车发票识别 https://market.aliyun.com/products/57124001/cmapi029811.html
     * @param string $file_url 文件获取url
     * @param string $o_id 订单号
     * @param int $is_old_compatible 兼容旧版
     * @throws
     */
    public function actionOcrCarInvoice($file_url = null, $o_id, $is_old_compatible = 1)
    {
        $log = new AliCarinfoGetLog();
        $log->o_id = $o_id;
        $log->uid = \Yii::$app->chedai_user->identity->u_id;
        $log->type = AliCarinfoGetLog::TYPE_FPOCRZW_9;
        $log->created_at = time();
        $log->request_file_url = $file_url;
        if ($file_url){
            $file_path = FileHelper::downloadTmpFileFromUrl($file_url);
            $body = AppStore::ocrCarInvoice($file_path);
            $arr = json_decode($body, true);
            $log->url = 'https://ocrapi-car-invoice.taobao.com';
//            $log->Message = $arr['Message'];
            $log->RequsetId = $log->request_id = isset($arr['sid'])?$arr['sid']:null;
            if (isset($arr['data'])){
                $log->data = json_encode($arr['data']);
                $log->fpdm = $log->invoiceDataCode = $arr['data']['发票代码'];
                $log->fphm = $log->invoice_number = $arr['data']['发票号码'];
                $log->kprq = $log->invoice_created_date = $log->billingTime = $arr['data']['开票日期'];
                $log->jshe = $arr['data']['价税合计（小写）'];
                $car = OrderCar::findOne(['ot_oid' => $o_id]);
                if ($car->ot_car_pose == '新车'){
                    $log->jshe = $arr['data']['不含税价'];
                }
                $log->engine_num = $log->engine_number = $arr['data']['发动机号码'];
                $log->vin = $arr['data']['车辆识别代号/车架号码'];
                $log->vehicle_type = $arr['data']['车辆类型'];
//                $log->model = $arr['data']['具体车型'];
                $log->model = $arr['data']['厂牌型号'];
                $log->xhdwmc = $arr['data']['销货单位名称'];
                $log->owner = $arr['data']['购买方名称'];
            }
        }else{
            $body = '';
        }
        $log->resp_body = $body;
        if (!$log->save()){
            throw new ApiException(201811141352, Model::getModelError($log));
        }
        if ($log->RequsetId){
            if ($is_old_compatible){
                $body = $this->actionInvoiceInfoForCom($o_id, AppStore::invoiceInfoForCom_TYPE_2, $log->fpdm, $log->fphm, $log->kprq, null, $log->jshe, $log->uid);
//                \Yii::$app->trigger(\Yii::$app::EVENT_AFTER_ACTION);
                echo $body;exit;
                /*$t = strtotime(date("Y-m-d"));
                $_t = strtotime($log->kprq);
                if ($t > $_t){
                    $body = $this->actionInvoiceInfoForCom($o_id, AppStore::invoiceInfoForCom_TYPE_2, $log->fpdm, $log->fphm, $log->kprq, null, $log->jshe, $log->uid);
                    echo $body;exit;
                }else{
                    $log->status = AliCarinfoGetLog::STATUS_LSFPZW_READY;
                    if (!$log->save()){
                        throw new ApiException(201812051103, Model::getModelError($log));
                    }
                }*/
            }else{
                return [
                    'o_id' => $o_id,
                    'iifc_type' => AppStore::invoiceInfoForCom_TYPE_2,
                    'invoiceCode' => $log->fpdm,
                    'invoiceNumber' => $log->fphm,
                    'billTime' => $log->kprq,
                    'checkCode' => null,
                    'invoiceAmount' => $log->jshe,
                    'uid' => $log->uid,
                ];
            }
        }
//        \Yii::$app->trigger(\Yii::$app::EVENT_AFTER_ACTION);
        echo $body;exit;
    }

    /**
     * 乐税发票真伪查验接口
     * @desc get/post https://market.aliyun.com/products/56928005/cmapi026291.html#sku=yuncode2029100000
     * @param string $o_id 订单号
     * @param int $iifc_type 乐税发票类型
     * @param string $invoiceCode 发票代码
     * @param string $invoiceNumber 发票号码
     * @param string $billTime 开票日期
     * @param string $checkCode 乐税发票类型1必填
     * @param string $invoiceAmount 乐税发票类型2必填
     * @param string $uid 用户id
     * @throws
     */
    public function actionInvoiceInfoForCom($o_id, $iifc_type = AppStore::invoiceInfoForCom_TYPE_2, $invoiceCode, $invoiceNumber, $billTime, $checkCode = null, $invoiceAmount = null, $uid)
    {
        $_request = [
            'invoiceCode' => $invoiceCode,
            'invoiceNumber' => $invoiceNumber,
            'billTime' => $billTime,
            'invoiceAmount' => $invoiceAmount,
        ];
        $request_file_url = Tools::arr2str($_request, " ");
        $log = AliCarinfoGetLog::findOne(['request_file_url' => $request_file_url]);
        if (!$log){
            $log = new AliCarinfoGetLog();
        }elseif($log->isFree == "N"){
//            \Yii::$app->trigger(\Yii::$app::EVENT_AFTER_ACTION);
            echo $log->resp_body;exit;
        }
        $log->request_file_url = $request_file_url;
        $log->o_id = $o_id;
        $log->uid = $uid;
        $log->type = AliCarinfoGetLog::TYPE_LSFPZW;
        $log->created_at = time();
        if (strlen($request_file_url) < 36){
            if ($log->save()){
                throw new ApiException(201901241458, "参数异常:".$request_file_url);
            }else{
                throw new \yii\db\Exception(Model::getModelError($log));
            }
        }
//        $body = AppStore::invoiceInfoForCom($iifc_type, $invoiceCode, $invoiceNumber, $billTime, $checkCode, $invoiceAmount);
        $body = AppStore::invoiceInfoForCom1($iifc_type, $invoiceCode, $invoiceNumber, $billTime, $checkCode, $invoiceAmount);
        $arr = json_decode($body, true);
        if (!isset($arr['invoiceResult'])){
            throw new ApiException(201901231827, "没有invoiceResult");
        }
        if (!is_array($arr['invoiceResult'])){
            $arr['invoiceResult'] = json_decode($arr['invoiceResult'], true, 512);
        }
//            $log->url = 'https://ls365vat.market.alicloudapi.com';
        $log->url = 'https://open.leshui365.com/api/invoiceInfoForCom';
        $log->RtnCode = isset($arr['RtnCode'])?$arr['RtnCode']:null;
        $log->resultCode = isset($arr['resultCode'])?$arr['resultCode']:null;
        $log->invoicefalseCode = isset($arr['invoicefalseCode'])?$arr['invoicefalseCode']:null;
        $log->resultMsg = isset($arr['resultMsg'])?$arr['resultMsg']:null;
        $log->invoiceName = isset($arr['invoiceName'])?$arr['invoiceName']:null;
        $log->invoiceResult = json_encode($arr['invoiceResult']);
        $log->isFree = isset($arr['isFree'])?$arr['isFree']:null;
        $log->invoiceDataCode = $log->fpdm = isset($arr['invoiceResult']['invoiceDataCode'])?$arr['invoiceResult']['invoiceDataCode']:null;
        $log->invoice_number = $log->fphm = isset($arr['invoiceResult']['invoiceNumber'])?$arr['invoiceResult']['invoiceNumber']:null;
        $log->billingTime = $log->kprq = $log->invoice_created_date = isset($arr['invoiceResult']['billingTime'])?$arr['invoiceResult']['billingTime']:null;
        $log->checkCode = isset($arr['invoiceResult']['checkCode'])?$arr['invoiceResult']['checkCode']:null;
        $log->vehicle_type = $log->car_type = isset($arr['invoiceResult']['vehicleType'])?$arr['invoiceResult']['vehicleType']:null; // 车辆类型
        $log->engine_num = $log->engine_number = isset($arr['invoiceResult']['engineNumber'])?$arr['invoiceResult']['engineNumber']:null; // 发动机号码
//        $log->plate_num = isset($arr['invoiceResult']['plateNo'])?$arr['invoiceResult']['plateNo']:null; // 老的车牌号
        $log->invoice_created_date = $log->kprq = $log->billingTime; // 发票开票日期
        $log->owner = isset($arr['invoiceResult']['purchaserName'])?$arr['invoiceResult']['purchaserName']:null;
        $log->vin = isset($arr['invoiceResult']['frameNumbr'])?$arr['invoiceResult']['frameNumbr']:null;
        $log->request_djzs_str= isset($arr['invoiceResult']['registNo'])?$arr['invoiceResult']['registNo']:null;
        $log->jshe= isset($arr['invoiceResult']['totalTaxSum'])?$arr['invoiceResult']['totalTaxSum']:null;
        $log->model= isset($arr['invoiceResult']['brandType'])?$arr['invoiceResult']['brandType']:null;
        if (isset($arr['invoiceResult']['salesName'])){
            $log->xhdwmc = $arr['invoiceResult']['salesName'];
        }
        if (isset($arr['invoiceResult']['secondHandMarket'])){
            $log->xhdwmc = $arr['invoiceResult']['secondHandMarket'];
        }
        if (isset($arr['invoiceResult']['secondHandMarketNo'])){
            $log->xhdwmc_no = $arr['invoiceResult']['secondHandMarketNo'];
        }elseif (isset($arr['invoiceResult']['salesTaxpayerNum'])){
            $log->xhdwmc_no = $arr['invoiceResult']['salesTaxpayerNum'];
        }
        $log->resp_body = $body;
        if (!$log->save()){
            throw new ApiException(201811141352, Model::getModelError($log));
        }
//        \Yii::$app->trigger(\Yii::$app::EVENT_AFTER_ACTION);
        echo $body;exit;
    }

    /**
     * wwei_二维码解码
     * @desc get/post https://market.aliyun.com/products/57126001/cmapi021204.html#sku=yuncode1520400000
     * @param string $file_url 二维码的图片网址
     * @param string $base64 二维码的图片
     * @param string $o_id 订单号
     */
    public function actionWweiDecodeErcode($file_url = null, $o_id, $base64 = null)
    {
        $log = new AliCarinfoGetLog();
        $log->o_id = $o_id;
        $log->uid = \Yii::$app->chedai_user->identity->u_id;
        $log->type = AliCarinfoGetLog::TYPE_WWEI_ENCODE_ERCODE;
        $log->created_at = time();
        $log->request_file_url = $file_url;
        $log->request_base64 = $base64;
        if ($file_url || $base64){
//            $file_path = FileHelper::downloadTmpFileFromUrl($file_url);
            if ($file_url){
                $file_path = FileHelper::downloadTmpFileFromUrl($file_url);
                $base64 = FileHelper::fileToBase64($file_path);
            }
            $body = AppStore::wweiEncodeErcode($base64);
            $arr = json_decode($body, true);
            $log->url = 'http://qrapi.market.alicloudapi.com';
            $log->resp_status = $arr['status'];
            $log->resultMsg = $arr['msg'];
            if ($log->resp_status = 1){
                if (!is_array($arr['data'])){
                    $data = json_decode($arr['data'], true);
                }else{
                    $data = $arr['data'];
                }
                $log->raw_text = isset($data['raw_text'])?$data['raw_text']:"";
                $log->raw_type = isset($data['raw_type'])?$data['raw_type']:"";;
            }else{
                $data = '';
            }
            $log->data = json_encode($data);
        }else{
            $body = '';
        }
        $log->resp_body = $body;
        $log->resp_status = (string)$log->resp_status;
        if (!$log->save()){
            throw new ApiException(201812141438, Model::getModelError($log));
        }
//        \Yii::$app->trigger(\Yii::$app::EVENT_AFTER_ACTION);
        echo $body;exit;
    }
}